/**
 * 
 */
package com.sevenpay.wx.jybcj.controller;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.bind.support.SessionStatus;
import org.springframework.web.servlet.ModelAndView;

import com.sevenpay.wx.connection.WxUrlConstants;
import com.sevenpay.wx.jybcj.SysConfig;
import com.sevenpay.wx.jybcj.bean.JybcjBean;
import com.sevenpay.wx.jybcj.commons.YbCode;
import com.sevenpay.wx.jybcj.service.JybcjService;

/**
 * @author kunwang.li
 *
 */
@Controller
@SessionAttributes(value = { "openId", "senderOpenId" })
@RequestMapping("/wx/jybcj")
public class JybcjController {

	private static Logger logger = LoggerFactory.getLogger(JybcjController.class);

	@Autowired
	private JybcjService jybcjService;

	@Autowired
	private SysConfig sysConfig;

	/*
	 * @ModelAttribute("openId") public String getOpenId() { return null; }
	 */

	/**
	 * got user authorize code用户第一次中公众号的菜单进入活动<br>
	 * 后续查看自己的集月饼的结果，也是通过此方法进入<br>
	 * 
	 * @param code
	 * @param state
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/entry")
	public ModelAndView entry(@RequestParam("code") String code, @RequestParam("state") String state,
			HttpSession session) throws Exception {

		logger.info("code[{}], state[{}]", code, state);

		ModelAndView mav = new ModelAndView();

		if (StringUtils.isBlank(code)) {
			// 用户没有接受授权，不能参与活动
			mav.setViewName("/wx/jybcj/" +"reject");
			return mav;
		}

		JybcjBean jybcjBean = jybcjService.entry(code, state);

		// TODO 是否需要限制已关注了公众号

		// 同时需要返回待鉴权的分享给url
		String shareUrl = WxUrlConstants.getUrl("authorize", sysConfig.getAppId(),
				URLEncoder.encode(sysConfig.getSendEntryUrl(), WxUrlConstants.charset), "snsapi_userinfo", "jybcj");
		jybcjBean.setShareUrl(shareUrl);

		mav.addObject("jybcjBean", jybcjBean);
		session.setAttribute("openId", jybcjBean.getYbUserInfo().getOpenId());

		if (null == jybcjBean.getYbInfo()) {
			// 还没有参与活动
			mav.setViewName("/wx/jybcj/" +"index");
		} else if (StringUtils.isBlank(jybcjBean.getYbInfo().getSelectYbCode())) {
			// 没有选择自己的月饼
			mav.setViewName("/wx/jybcj/" +"select");
		} else {
			// 进入收集月饼结果页面
			mav.setViewName("/wx/jybcj/" +"collect");
		}
		return mav;
	}

	/**
	 * 开启集月饼活动
	 * 
	 * @param openId
	 * @return
	 */
	public ModelAndView start(@ModelAttribute("openId") String openId) {
		ModelAndView mav = new ModelAndView();
		JybcjBean jybcjBean = this.jybcjService.start(openId);
		mav.addObject("jybcjBean", jybcjBean);
		mav.setViewName("/wx/jybcj/" +"select");
		return mav;
	}

	/**
	 * 发起活动的人自己选择月饼
	 * 
	 * @param openId
	 * @param ybCode
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	@RequestMapping("/selectYb")
	public ModelAndView selectYb(@ModelAttribute("openId") String openId, @RequestParam("ybCode") YbCode ybCode)
			throws UnsupportedEncodingException {
		logger.info("openId[{}], ybCode[{}]", openId, ybCode);
		ModelAndView mav = new ModelAndView();

		this.jybcjService.selectYb(openId, ybCode);
		JybcjBean jybcjBean = jybcjService.entry(openId);

		String shareUrl = WxUrlConstants.getUrl("authorize", sysConfig.getAppId(),
				URLEncoder.encode(sysConfig.getSendEntryUrl(), WxUrlConstants.charset), "snsapi_userinfo", "jybcj");
		jybcjBean.setShareUrl(shareUrl);
		mav.addObject("jybcjBean", jybcjBean);
		mav.setViewName("/wx/jybcj/" +"collect");
		return mav;
	}

	/**
	 * 点击好友分享的连接进入到活动页，给好友送月饼
	 * 
	 * @param code
	 * @param state
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/sendEntry")
	public ModelAndView sendEntry(@RequestParam("openId") String openId, @RequestParam("code") String code,
			@RequestParam("state") String state, HttpSession session) throws Exception {

		logger.info("openId[{}], code[{}], state[{}]", openId, code, state);
		ModelAndView mav = new ModelAndView();
		if (StringUtils.isBlank(code)) {
			// 用户没有接受授权，不能参与活动
			mav.setViewName("/wx/jybcj/" +"reject");
			return mav;
		}

		// 是否需要限制已关注了工作号
		String senderOpenId = this.jybcjService.sendEntry(code, state);
		session.setAttribute("senderOpenId", senderOpenId);
		JybcjBean jybcjBean = jybcjService.entry(openId);

		if (null == jybcjBean.getYbInfo()) {
			mav.setViewName("/wx/jybcj/" +"reject");
		} else {
			mav.addObject("jybcjBean", jybcjBean);
			mav.setViewName("/wx/jybcj/" +"collect");
		}
		return mav;
	}

	@RequestMapping("/sendEntryRefresh")
	public ModelAndView sendEntryRefresh(@RequestParam("openId") String openId,
			@ModelAttribute("senderOpenId") String senderOpenId) throws Exception {

		ModelAndView mav = new ModelAndView();
		if (StringUtils.isBlank(senderOpenId)) {
			// 用户没有接受授权，不能参与活动
			mav.setViewName("/wx/jybcj/" +"reject");
			return mav;
		}

		JybcjBean jybcjBean = jybcjService.entry(openId);

		if (null == jybcjBean.getYbInfo()) {
			mav.setViewName("/wx/jybcj/" +"reject");
		} else {
			mav.addObject("jybcjBean", jybcjBean);
			mav.setViewName("/wx/jybcj/" +"collect");
		}
		return mav;
	}

	/**
	 * 送月饼
	 * 
	 * @return
	 */
	@RequestMapping("/sendYb")
	@ResponseBody
	public boolean sendYb(@RequestParam("openId") String openId, @RequestParam("ybCode") YbCode ybCode,
			@ModelAttribute("senderOpenId") String senderOpenId, SessionStatus status) {

		status.setComplete();
		return this.jybcjService.sendYb(openId, senderOpenId, ybCode);
	}

	/**
	 * 抽奖
	 * 
	 * @return
	 */
	@RequestMapping("/cj")
	@ResponseBody
	public String cj(@RequestParam("openId") String openId, @RequestParam("cjResult") String cjResult) {

		return "success";
	}

	public JybcjService getJybcjService() {
		return jybcjService;
	}

	public void setJybcjService(JybcjService jybcjService) {
		this.jybcjService = jybcjService;
	}

}
